package com.acidsweet.zerolrucachesample;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.acidsweet.zerolrucache.ZeroLruCache;
import com.acidsweet.zerolrucache.core.CacheEvent;
import com.acidsweet.zerolrucache.core.ILruCache;
import com.acidsweet.zerolrucache.core.OnEventListener;
import com.acidsweet.zerolrucache.util.Converter;

import java.io.IOException;
import java.io.Serializable;

/**
 * Created by jin on 16/10/20.
 */

public class DetailActivity extends Activity implements View.OnClickListener{
    private static final String TAG=DetailActivity.class.getSimpleName();
    private static final int Int = 1;
    private static final double Dou = 3.14;
    private static final float Flo = (float) 3.1415;
    private static final String Str = "Hello World!";
    private static final boolean Bool = false;
    private static User user;
    public static class User implements Serializable{
        public String name;
        public String pwd;

        public User(String name, String pwd) {
            this.name = name;
            this.pwd = pwd;
        }

        @Override
        public String toString() {
            StringBuffer sb = new StringBuffer();
            sb.append("\nUSER:");
            sb.append("\n{");
            sb.append("\n    NAME:" + name);
            sb.append("\n    PWD:" + pwd);
            sb.append("\n}");
            return sb.toString();
        }
    }

    private TextView tv;
    private ImageView bitmap_iv;
    private ImageView drawable_iv;
    private Button save_btn,load_btn;
    private String mode;
    private Bitmap bitmap;
    private Drawable drawable;
    private ILruCache mLruCache;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail);
        tv = (TextView) findViewById(R.id.result_text);
        bitmap_iv = (ImageView) findViewById(R.id.result_bitmap);
        drawable_iv = (ImageView) findViewById(R.id.result_drawable);
        save_btn=(Button)findViewById(R.id.detail_save);
        load_btn=(Button)findViewById(R.id.detail_load);
        save_btn.setOnClickListener(this);
        load_btn.setOnClickListener(this);
        Intent in = getIntent();
        mode = in.getStringExtra("mode");
        setTitle(mode);
        StringBuffer sb = new StringBuffer();
        sb.append("\nINT:" + Int);
        sb.append("\nDOUBLE:" + Dou);
        sb.append("\nFLOAT:" + Flo);
        sb.append("\nSTRING:" + Str);
        sb.append("\nBOOLEAN:" + Boolean.toString(Bool));
        user= new User("acidsweet", "123456");
        sb.append(user.toString());
        tv.setText(sb.toString());
        bitmap_iv.setImageResource(R.drawable.bitmap);
        drawable_iv.setImageResource(R.drawable.drawable);
        bitmap = drawableToBitmap(bitmap_iv.getDrawable());
        drawable = drawable_iv.getDrawable();

        if(MainActivity.mCacheModes[0].equals(mode))
        {
            mLruCache= ZeroLruCache.getDefaultMemoryLruCache(DetailActivity.this.getApplicationContext());
        }
    }

    public static Bitmap drawableToBitmap(Drawable drawable) {
        // 取 drawable 的长宽
        int w = drawable.getIntrinsicWidth();
        int h = drawable.getIntrinsicHeight();
        // 取 drawable 的颜色格式
        Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
                : Bitmap.Config.RGB_565;
        // 建立对应 bitmap
        Bitmap bitmap = Bitmap.createBitmap(w, h, config);
        // 建立对应 bitmap 的画布
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, w, h);
        // 把 drawable 内容画到画布中
        drawable.draw(canvas);
        return bitmap;
    }

    @Override
    public void onClick(View v) {
        int id=v.getId();
        switch(id)
        {
            case R.id.detail_save:
                save();
                break;
            case R.id.detail_load:
                load();
                break;

        }

    }
    private void save()
    {
        Log.d(TAG,"save");
        mLruCache.put("INT", Converter.Int2Bytes(Int),onEventListener);
        mLruCache.put("DOUBLE",Converter.Double2Bytes(Dou),onEventListener);
        mLruCache.put("FLOAT",Converter.Float2Bytes(Flo),onEventListener);
        mLruCache.put("STRING",Converter.String2Bytes(Str),onEventListener);
        mLruCache.put("BOOLEAN",Converter.Boolean2Bytes(Bool),onEventListener);
        try{
        mLruCache.put("USER",Converter.Serializable2Bytes(user),onEventListener);
        }catch (IOException e)
        {
            e.printStackTrace();
        }
        mLruCache.put("BITMAP",Converter.Bitmap2Bytes(bitmap),onEventListener);
        mLruCache.put("DRAWABLE",Converter.Drawable2Bytes(drawable),onEventListener);
    }
    private void load()
    {
        Log.d(TAG,"load");
        mLruCache.get("INT",onEventListener);
        mLruCache.get("DOUBLE",onEventListener);
        mLruCache.get("FLOAT",onEventListener);
        mLruCache.get("STRING",onEventListener);
        mLruCache.get("BOOLEAN",onEventListener);
        mLruCache.get("USER",onEventListener);
        mLruCache.get("BITMAP",onEventListener);
        mLruCache.get("DRAWABLE",onEventListener);
        (new Handler()).postDelayed(new Runnable() {
            @Override
            public void run() {
//                ResultDialog dialog=new ResultDialog(DetailActivity.this);
//                dialog.setData(load_sb.toString(),load_bitmap,load_drawable);
//                dialog.show();
                LayoutInflater inflater=getLayoutInflater();
                View view=inflater.inflate(R.layout.resultview,null);
                TextView tv;
                ImageView bitmap_iv;
                ImageView drawable_iv;
                tv = (TextView) view.findViewById(R.id.result_text);
                bitmap_iv = (ImageView) view.findViewById(R.id.result_bitmap);
                drawable_iv = (ImageView) view.findViewById(R.id.result_drawable);
                tv.setText(load_sb.toString());
                bitmap_iv.setImageBitmap(load_bitmap);
                drawable_iv.setImageDrawable(load_drawable);
                new AlertDialog.Builder(DetailActivity.this)
                        .setTitle("Load Result:")
                        .setView(view)
                        .show();
            }
        },2000);
    }
    public StringBuffer load_sb=new StringBuffer();
    public Bitmap load_bitmap;
    public Drawable load_drawable;
    private OnEventListener onEventListener=new OnEventListener() {

        @Override
        public void onEventSucc(CacheEvent event) {
            if(CacheEvent.ACTION_PUT==event.action)
                Log.d(TAG,"onEventSucc action="+event.action+" key="+event.key);
            else if(CacheEvent.ACTION_GET==event.action)
            {
                Log.d(TAG,"onEventSucc action="+event.action+" key="+event.key);
                byte[] value=event.value;
                switch(event.key)
                {
                    case "INT":
                        load_sb.append("\nINT:"+Converter.Bytes2Int(value));
                        break;
                    case "DOUBLE":
                        load_sb.append("\nDOUBLE:"+Converter.Bytes2Double(value));
                        break;
                    case "FLOAT":
                        load_sb.append("\nFLOAT:"+Converter.Bytes2Float(value));
                        break;
                    case "STRING":
                        load_sb.append("\nSTRING:"+Converter.Bytes2String(value));
                        break;
                    case "BOOLEAN":
                        load_sb.append("\nBOOLEAN:"+Converter.Bytes2Boolean(value));
                        break;
                    case "USER":
                        try {
                            User user=(User)Converter.Bytes2Serializable(value);
                            load_sb.append(user.toString());
                        } catch (IOException e) {
                            e.printStackTrace();
                        } catch (ClassNotFoundException e) {
                            e.printStackTrace();
                        }

                        break;
                    case "BITMAP":
                        load_bitmap=Converter.Bytes2Bitmap(value);
                        break;
                    case "DRAWABLE":
                        load_drawable=Converter.Bytes2Drawable(value);
                        break;

                }

            }
        }

        @Override
        public void onEventFail(Exception error) {

        }
    };
}
